package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/satori/go.uuid"
	"github.com/smartwalle/alipay/v3"
	"my_pro/model"
	"my_pro/schemas"
	"my_pro/utils"
	"net/http"
	"strconv"
	"time"
)

// 总路由分发
func NewPath(newsGrp *gin.RouterGroup) {
	//newsGrp.Use().POST("/addnews", addNews)
	//newsGrp.Use().GET("/getnews", getNews)
	////获取支付宝地址
	newsGrp.Use().GET("/getpayurl", getpayurl)
	//回调接口
	newsGrp.Use().GET("/callback", callback)
	newsGrp.Use().POST("/sendTargetLand", sendTargetLand)
	newsGrp.Use().GET("/InterfaceCode", InterfaceCode)
	newsGrp.Use().GET("/socketConn", socketConn)
	newsGrp.Use().GET("/SocketSend", SocketSend)
	newsGrp.Use().GET("/AllTask", AllTask)

}

// 获取支付宝地址
func getpayurl(c *gin.Context) {
	money := c.Query("money")
	utils.Init()
	var p = alipay.TradePagePay{}
	p.NotifyURL = "http://127.0.0.1:8000/new/callback"
	p.ReturnURL = "http://127.0.0.1:8000/new/callback"
	p.Subject = "要充值"
	p.OutTradeNo = string((utils.RandInt(100000, 999999)))
	p.TotalAmount = money
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := utils.Client.TradePagePay(p)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 20010,
			"mes":  "获取",
		})
		return
	}
	fmt.Println(url, "================")
	reurl := url.Scheme + "://" + url.Host + url.Path + "?" + url.RawQuery
	c.JSON(200, gin.H{
		"code": 200,
		"url":  reurl,
	})
}

// 支付宝回调接口
func callback(c *gin.Context) {
	//难签
	//uid := c.Query("uid")
	order, err := utils.Client.GetTradeNotification(c.Request)
	alipay.AckNotification(c.Writer) // 确认收到通知消息
	fmt.Println(err, order)
	if order == nil {
		fmt.Println("验证失败")
	} else {
		fmt.Println(order)
	}
}

// 生成订单
func InterfaceCode(c *gin.Context) {
	uid := c.Query("uid")
	id := uuid.NewV4()
	ids := id.String()
	//fmt.Println(ids)
	r := utils.RedisPool
	r.Setex(ids, 30, uid)
	c.JSON(200, gin.H{
		"ids": ids,
	})

}

// 发布表地
func sendTargetLand(c *gin.Context) {
	r := utils.RedisPool
	var Target schemas.Target
	_ = c.Bind(&Target)
	uuidcode := r.Get(Target.Uuid)
	if uuidcode == "" {
		c.JSON(200, gin.H{
			"code": 10022,
			"msg":  "提交失败，重新提交",
		})
		return
	}
	r.StrDel(Target.Uuid)
	snow := strconv.FormatInt((snowflake()), 10)
	code := (snowflake() % 3)
	if code == 0 {
		sql := "INSERT INTO target_land0(code,Userid,money) values (?,?,?)"
		err := model.DB.Exec(sql, snow, Target.Userid, Target.Money)
		fmt.Println(err)
		if err.Error != nil {
			fmt.Println(err.Error)
			return
		}
	}
	if code == 1 {
		sql := "INSERT INTO target_land1(code,Userid,money) values (?,?,?)"
		err := model.DB.Exec(sql, snow, Target.Userid, Target.Money)
		fmt.Println(err)
		if err.Error != nil {
			fmt.Println(err.Error)
			return
		}
	}
	if code == 2 {
		sql := "INSERT INTO target_land2(code,Userid,money) values (?,?,?)"
		err := model.DB.Exec(sql, snow, Target.Userid, Target.Money)
		fmt.Println(err)
		if err.Error != nil {
			fmt.Println(err.Error)
			return
		}
	}
	num := code%5 + 1
	snowcode, _ := strconv.Atoi(snow)
	r.ListAdd("snowcode", snowcode)
	utils.AuditTask()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发表成功",
		"num":  num,
	})
}

// 雪花算法id
func snowflake() int64 {
	worker, err := utils.NewWorker(0)
	if err != nil {
		fmt.Println(err)
	}
	id := worker.NextId()
	fmt.Println(id)
	return id

}

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:   1024,
		WriteBufferSize:  1024,
		CheckOrigin:      func(r *http.Request) bool { return true },
		HandshakeTimeout: time.Duration(time.Second * 5),
	}
)

var socketLink = make(map[string]*websocket.Conn)

func socketConn(c *gin.Context) {
	kefuid := c.Query("id")
	//建立连接
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println(err, "Upgrade failed")
		c.JSON(200, gin.H{
			"code": 10010,
			"mes":  "连接错误",
		})
	}
	//存储在map中
	socketLink[kefuid] = conn
}

func SocketSend(c *gin.Context) {
	//从客户端获取消息
	mes := c.Query("mes")
	kefuid := c.Query("id")
	//从map中获取连接
	conn := socketLink[kefuid]
	//发送消息给客户端
	conn.WriteMessage(1, []byte(mes))
}

// 要审核的
func AllTask(c *gin.Context) {
	TargetTask := schemas.TargetTask{}
	var lists []interface{}
	id := c.Query("id")
	auditid := "audit" + id
	r := utils.RedisPool
	res := r.ListGetAll2(auditid)
	for _, i := range res {
		num, _ := strconv.Atoi(i)
		table := "target_land" + strconv.Itoa(num%3)
		sql := fmt.Sprintf("SELECT * from %s where code='%s'", table, i)
		model.DB.Raw(sql).Scan(&TargetTask)
		lists = append(lists, TargetTask)
	}
	c.JSON(200, gin.H{
		"list": lists,
	})
}
